package com.example.mediastore.utils;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.graphics.pdf.PdfRenderer;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;


import com.example.mediastore.R;
import com.example.mediastore.bean.FileBean;
import com.example.mediastore.constant.Constant;
import com.example.mediastore.player.MusicPlayerActivity;
import com.example.mediastore.player.VideoPlayerActivity;
import com.example.mediastore.thread.MyThreadPool;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;

public class CommonUtil {

    // 实例化线程池类
    static MyThreadPool threadPool = new MyThreadPool();



    //获取文件扩展名
    public static String getFileExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf(".");
        if (lastDotIndex != -1) {
            return fileName.substring(lastDotIndex + 1);
        }
        return "";
    }

    /**
     * 获取音视频时长的
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    public static String getMediaDuration(String filePath) throws IOException {
        MediaMetadataRetriever retriever = null;
        try {
            retriever = new MediaMetadataRetriever();
            retriever.setDataSource(filePath);
            String durationStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            if (TextUtils.isEmpty(durationStr)) {
                durationStr = "0";
            }
            long duration = Long.parseLong(durationStr);

            long hours = TimeUnit.MILLISECONDS.toHours(duration);
            long minutes = TimeUnit.MILLISECONDS.toMinutes(duration) % 60;
            long seconds = TimeUnit.MILLISECONDS.toSeconds(duration) % 60;

            return String.format(Locale.getDefault(), Constant.TIME_FORMAT, hours, minutes, seconds);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return Constant.ZERO_FORMAT;
    }

    /**
     * 获取文件大小
     *
     * @param fileSize
     * @return
     */
    @SuppressLint("DefaultLocale")
    public static String getFileSizeString(long fileSize) {
        if (fileSize < 1024) {
            return fileSize + "B";
        } else if (fileSize < 1048576) {
            return String.format("%.1fKB", (double) fileSize / 1024);
        } else {
            return String.format("%.1fMB", (double) fileSize / 1048576);
        }
    }

    /**
     * 格式化时间
     *
     * @param date
     * @return
     */
    public static String format(Date date) {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
        return simpleDateFormat.format(date);
    }

    /**
     * 长时间显示的 Toast 消息
     *
     * @param context
     * @param msg
     */
    public static void toastLong(Context context, String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();

    }

    /**
     * 短时间显示的 Toast 消息
     *
     * @param context
     * @param msg
     */
    public static void toastShort(Context context, String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();

    }


    /**
     * 获取音视频的封面
     *
     * @param videoPath
     * @return
     */
    public static Bitmap getVideoThumbnail(String videoPath) {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        retriever.setDataSource(videoPath);

        // 获取第一帧图像
        Bitmap thumbnail = retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
        try {
            retriever.release();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return thumbnail;
    }

    /**
     * 获取pdf封面
     */
    public static Bitmap getPDFCover(Context context,String pathToPDF) {
        Bitmap cover = null;
        try {
            ParcelFileDescriptor fileDescriptor = ParcelFileDescriptor.open(new File(pathToPDF), ParcelFileDescriptor.MODE_READ_ONLY);
            PdfRenderer renderer = new PdfRenderer(fileDescriptor);
            if (renderer.getPageCount() > 0) {
                PdfRenderer.Page page = renderer.openPage(0);
                int width = context.getResources().getDisplayMetrics().densityDpi / 72 * page.getWidth();
                int height = context.getResources().getDisplayMetrics().densityDpi / 72 * page.getHeight();
                cover = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                page.render(cover, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
                page.close();
            }
            renderer.close();
            fileDescriptor.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cover;
    }
    private static byte[] bitmapToByteArray(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        return stream.toByteArray();
    }


    /**
     * 打开文件
     *
     * @param filePath
     * @param fileName
     */
    public static void openFile(Context context, String filePath, String fileName, String time) {

        File file = new File(filePath);
        if (file.exists()) {
            Intent intent;
            if (fileName.endsWith(".mp4")) {
                intent = new Intent(context, VideoPlayerActivity.class);
                intent.putExtra("uri", filePath);
                intent.putExtra("name", fileName);
                context.startActivity(intent);
            } else if (fileName.endsWith(".mp3")) {
                intent = new Intent(context, MusicPlayerActivity.class);
                intent.putExtra("uri", filePath);
                intent.putExtra("name", fileName);
                intent.putExtra("time", time);
                context.startActivity(intent);
            } else {
                intent = new Intent(Intent.ACTION_VIEW);
                Uri uri = FileProvider.getUriForFile(context, Constant.AUTHORITY, file);
                intent.setDataAndType(uri, getMimeType(filePath));
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                context.startActivity(intent);
            }

        } else {
            CommonUtil.toastShort(context, Constant.FILE_NOT_EXIST);
        }
    }

    /**
     * 获取文件的MIME类型
     *
     * @param filePath
     * @return
     */
    public static String getMimeType(String filePath) {
        String mimeType = "*/*";
        String extension = MimeTypeMap.getFileExtensionFromUrl(filePath);
        if (extension != null) {
            mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        }
        return mimeType;
    }

    /**
     * 分享文件
     */
    public static void shareFile(String filePath, Context context) {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        File file = new File(filePath);
        Uri contentUri = FileProvider.getUriForFile(context, Constant.AUTHORITY, file);
        shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        context.startActivity(shareIntent);
    }


    @SuppressLint("SetTextI18n")
    public static void openDialog(ImageView iv_img, String createTime, String updateTime, String length, TextView... textViews) {
        // 创建AlertDialog.Builder对象
        View customView = LayoutInflater.from(textViews[0].getContext()).inflate(R.layout.custom_dialog, null);
        ImageView dialogImage = customView.findViewById(R.id.dialog_image);
        TextView dialogMessage = customView.findViewById(R.id.dialog_message);

        // 设置对话框的图片和消息内容
        dialogImage.setImageDrawable(iv_img.getDrawable());
        dialogMessage.setText("\n" +
                Constant.FILE_NAME + textViews[0].getText() + "\n" +
                Constant.FILE_PATH + textViews[1].getText() + "\n" +
                Constant.CREATE_TIME + (createTime != null ? createTime : "") + "\n" +
                Constant.UPDATE_TIME + (updateTime != null ? updateTime : "") + "\n" +
                Constant.FILE_LENGTH + length);

        dialogMessage.setPadding(30, 0, 0, 0);
        dialogMessage.setTextSize(15);

        // 创建AlertDialog并将自定义视图添加到其中
        AlertDialog.Builder builder = new AlertDialog.Builder(textViews[0].getContext());
        builder.setTitle(Constant.DETAIL);
        builder.setView(customView);


        builder.setPositiveButton(Constant.YES, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss(); // 关闭对话框
                CommonUtil.toastShort(iv_img.getContext(), Constant.I_KNOW);
            }
        });
        AlertDialog dialog = builder.create();
        // 设置进入动画效果
        Objects.requireNonNull(dialog.getWindow()).getAttributes().windowAnimations = R.style.DialogEnterAnimation;
        dialog.show();
        // 设置对话框的背景样式
        @SuppressLint("ResourceType") Drawable dialogBackground = ContextCompat.getDrawable(textViews[0].getContext(), R.xml.dialog_style);
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(dialogBackground);
        // 设置退出动画效果
        dialog.getWindow().getAttributes().windowAnimations = R.style.DialogExitAnimation;
    }

    /**
     * 提示拒绝权限窗口
     */

    public static void showPermissionRationale(Activity activity) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("权限申请");
        builder.setMessage("您需要授予存储权限才能进行文件操作，是否前往设置页面授予权限？");
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 引导用户前往设置页面手动授予权限
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                        Uri.parse("package:" + activity.getPackageName()));
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                activity.startActivity(intent);
            }
        });
        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 用户点击否
                Toast.makeText(activity, "您拒绝了存储权限", Toast.LENGTH_SHORT).show();
            }
        });
        builder.show();
    }


    /**
     * 开始加载动画
     */
    private static ObjectAnimator rotationAnimator;

    public static void startRotationAnimation(ImageView animationView, TextView loadingText) {
        animationView.setVisibility(View.VISIBLE);
        loadingText.setText(R.string.loading);
        loadingText.setVisibility(View.VISIBLE);
        // 设置旋转动画
        rotationAnimator = ObjectAnimator.ofFloat(animationView, "rotation", 0f, 360f);
        //设置动画时长
        rotationAnimator.setDuration(3000);
        // 设置动画无限重复
        rotationAnimator.setRepeatCount(ObjectAnimator.INFINITE);
        // 设置线性插值器
        rotationAnimator.setInterpolator(new LinearInterpolator());
        rotationAnimator.start();
    }


    /**
     * 结束加载动画
     */
    public static void stopRotationAnimation(ImageView animationView, TextView loadingText) {
        rotationAnimator.cancel();
        loadingText.setVisibility(View.GONE);
        animationView.setVisibility(View.GONE);
    }

    /**
     * 扫描文件
     */
    public static class FileSearcher {

        private ConcurrentHashMap<String, List<FileBean>> hashMap;
        private static String[] typeList;
        private static Integer[] iconList;

        public FileSearcher(ConcurrentHashMap<String, List<FileBean>> hashMap, String[] typeList, Integer[] iconList) {
            this.hashMap = hashMap;
            this.typeList = typeList;
            this.iconList = iconList;
        }


        public static List<FileBean> searchFiles(File directory) throws IOException {
            List<FileBean> fileList = new ArrayList<>();
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        fileList.addAll(searchFiles(file)); // 递归搜索子目录，并将结果添加到集合中
                    } else {
                        String extension = getFileExtension(file.getName());
                        switch (extension.toLowerCase()) {
                            case "pdf":
                                fileList.add(createFileBean(file, typeList[1], iconList[0]));
                                break;
                            case "pptx":
                                fileList.add(createFileBean(file, typeList[2], iconList[1]));
                                break;
                            case "docx":
                                fileList.add(createFileBean(file, typeList[3], iconList[2]));
                                break;
                            case "xls":
                            case "xlsx":
                                fileList.add(createFileBean(file, typeList[4], iconList[3]));
                                break;
                            case "ett":
                                fileList.add(createFileBean(file, typeList[5], iconList[4]));
                                break;
                            case "mp3":
                            case "wav":
                                fileList.add(createFileBean(file, typeList[6], iconList[5]));
                                break;
                            case "mp4":
                            case "avi":
                                fileList.add(createFileBean(file, typeList[7], iconList[6]));
                                break;
                            case "jpg":
                            case "png":
                                fileList.add(createFileBean(file, typeList[8], iconList[7]));
                                break;

                        }
                    }
                }
            }
            return fileList;
        }


    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @SuppressLint("Range")
    public static List<FileBean> scanMediaStore(Activity activity, ConcurrentHashMap<String, List<FileBean>> hashMap) throws Exception {
        ContentResolver contentResolver = activity.getContentResolver();
        // 创建查询的URI
        Uri queryUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);

        Log.d("xiaoxulu", "queryUri: " + queryUri);
        List<FileBean> fileBeans = new ArrayList<>();


        String[] projection = new String[]{
                MediaStore.Files.FileColumns._ID,
                MediaStore.Files.FileColumns.DATA,
                MediaStore.Files.FileColumns.DISPLAY_NAME,
                MediaStore.Files.FileColumns.SIZE,
                MediaStore.Files.FileColumns.MIME_TYPE,
                MediaStore.Files.FileColumns.DATE_ADDED,
                MediaStore.Files.FileColumns.DATE_MODIFIED,
        };

        String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + " IN (" +
                "'audio/mpeg'," +
                " 'video/mp4'," +
                "'image/jpeg'," +
                "'application/pdf'," +
                "'application/vnd.openxmlformats-officedocument.presentationml.presentation'," +
                "'application/vnd.openxmlformats-officedocument.wordprocessingml.document'," +
                "'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'," +
                "'application/ett')";

        Cursor cursor = contentResolver.query(
                queryUri,
                projection,
                selectionMimeType,
                null,
                MediaStore.Files.FileColumns.DATE_ADDED + " DESC"
        );

        if (cursor != null) {
            while (cursor.moveToNext()) {
                // 获取文件信息
                String path = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA));
                String title = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME));
                long size = cursor.getLong(cursor.getColumnIndex(MediaStore.Files.FileColumns.SIZE));
                String mimeType = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.MIME_TYPE));
                long dateAdded = cursor.getLong(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATE_ADDED))*1000;
                long dateModified = cursor.getLong(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATE_MODIFIED))*1000;

                Log.d(Constant.TAG, "dateAdded: "+format(new Date(dateAdded)));
                // 根据文件类型将其归类存储
                String type = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
                FileBean fileBean = new FileBean();
                fileBean.setName(title);
                fileBean.setPath(path);
                fileBean.setCreateTime(CommonUtil.format(new java.sql.Date(dateAdded)));
                fileBean.setUpdateTime(CommonUtil.format(new java.sql.Date(dateModified)));
                fileBean.setLength(CommonUtil.getFileSizeString(size));
                fileBean.setFileType(type);
                fileBean.setIcon(CommonUtil.setIcon(mimeType));






                if (hashMap.containsKey(type)) {
                    hashMap.get(type).add(fileBean);
                } else {
                    List<FileBean> fileList = new ArrayList<>();
                    fileList.add(fileBean);
                    hashMap.put(type, fileList);
                }
                fileBeans.add(fileBean);

            }
            int count = cursor.getCount();

            cursor.close();

        }
        Log.d("xiaoxulu", "fileBeans.size: " + fileBeans.size());

        return fileBeans;

}



    public static FileBean createFileBean(File file, String fileType, Integer icon) {
        // 创建文件对象
        FileBean fileBean = new FileBean();
        // 设置文件属性
        fileBean.setName(file.getName());
        fileBean.setPath(file.getPath());
        fileBean.setFileType(fileType.toLowerCase());
        fileBean.setIcon(icon);
        fileBean.setLength(CommonUtil.getFileSizeString(file.length()));
        fileBean.setCreateTime(CommonUtil.format(new Date(file.lastModified())));
        fileBean.setUpdateTime(CommonUtil.format(new Date(file.lastModified())));

        return fileBean;
    }





    /**
     * 根据类型设置对应的图标
     */
    public static Integer setIcon(String mimeType) {
        // 设置图标
        if (mimeType != null && !mimeType.isEmpty()) {
            if (mimeType.startsWith("audio/")) {
                return R.mipmap.mp3;
            } else if (mimeType.startsWith("video/")) {
                return R.mipmap.mp4;
            } else if (mimeType.startsWith("image/")) {
                return R.mipmap.image;
            } else if (mimeType.equals("application/pdf")) {
                return R.mipmap.pdf;
            } else if (mimeType.equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) {
                return R.mipmap.ppt;
            } else if (mimeType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
                return R.mipmap.doc;
            } else if (mimeType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
                return R.mipmap.excel;
            }
        }
        return 0;
    }

    /**
     * 扫描完成通知
     */
    private static final int DATABASE_QUERY_NOTIFICATION_ID = 1;

    public static void sendDatabaseQueryNotification(int count,Activity activity) {
        NotificationManager notificationManager = (NotificationManager) activity.getSystemService(activity.NOTIFICATION_SERVICE);

        if (notificationManager == null) {
            return;
        }

        String channelId =  String.valueOf(R.string.app_name);
        String channelName = String.valueOf(R.string.app_name);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(channelId, channelName, importance);
            notificationManager.createNotificationChannel(mChannel);
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(activity, channelId)
                .setSmallIcon(R.mipmap.icon)
                .setContentTitle("扫描完成")
                .setContentText("共扫描到"+count+"个文件")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setAutoCancel(true);

        notificationManager.notify(DATABASE_QUERY_NOTIFICATION_ID, builder.build());
    }


}